/** file Vibrato.cpp
    author belot.nicolas
*/

#include "Vibrato.h"
#include <cmath>
namespace libtrckr {
	Vibrato::Vibrato():c(1.0,1024){
		duration = elapsed = speed= .0;
		max_ratio = 1.;
		linear = false;
	}

	Vibrato::Vibrato(const Vibrato& v):c(v.c){
		duration = v.duration;
		elapsed = v.elapsed;
		speed= v.speed;
		linear = v.linear;
		max_ratio = v.max_ratio;
	}

	Vibrato::~Vibrato(){

	}

	void Vibrato::Tune(DynArray<double> conf){
		duration=conf[0];//alsa know as speed;
		max_ratio=conf[1];//depth
		speed = (1.0 - max_ratio) / duration;
		std::cout << "vitesse : " << speed << std::endl;
		linear=(conf[2]>0.);
	}


	Buffer& Vibrato::apply(Buffer& b, int *size){
		double ratio=0.;
		if(linear){
			double reste = remainder(elapsed,2*duration);
			if(reste < duration){
				ratio = 1. + (speed * (reste) );
			}else if(reste==duration){
				ratio=max_ratio;
			} else{
				ratio = 1. + (speed * (duration - (reste - duration)));
			}
		}else{
			ratio = 1. + (speed * abs( sin(elapsed * M_PI/ duration)));
		}
		c.ratio(ratio);
		Buffer b2(*size);
		for(uint i=0;i<*size;i++){
			b2[i]=b[i];
		}
		int retsize=c.convert(b2,b);
		*size=retsize;
		elapsed+=*size;
		return b;
	}
}
